import json
import os
from datetime import datetime
from typing import List, Dict

class LogService:
    """日志记录服务"""
    
    def __init__(self, log_file='logs/detection.log'):
        self.log_file = log_file
        os.makedirs(os.path.dirname(log_file), exist_ok=True)
    
    def log_detection(self, result: Dict):
        """记录检测结果"""
        log_entry = {
            'timestamp': datetime.now().isoformat(),
            'type': result.get('type'),
            'count': result.get('count', 0),
            'risk_level': result.get('risk_level'),
            'detected_items': result.get('detected_items', [])
        }
        
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(json.dumps(log_entry, ensure_ascii=False) + '\n')
    
    def get_recent_logs(self, limit=100) -> List[Dict]:
        """获取最近的日志"""
        logs = []
        if os.path.exists(self.log_file):
            with open(self.log_file, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                for line in lines[-limit:]:
                    try:
                        logs.append(json.loads(line.strip()))
                    except:
                        continue
        return logs[::-1]  # 倒序，最新的在前

